<?php
/**
 * ValidationExceptionHandler.php
 * ==============================================
 * Copy right 2021  by tianmtech.cn
 * ----------------------------------------------
 * This is not a free software, without any authorization is not allowed to use and spread.
 * ==============================================
 * @desc :  validate规则验证异常处理包
 * @author: xuxiaoyang@tianmtech.cn
 * @version: v1.0.0
 * @since: 2021/12/29 下午5:45
 */

declare(strict_types=1);

namespace App\Exception\Handler;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Utils\Codec\Json;
use Hyperf\Validation\ValidationExceptionHandler as Handler;
use Psr\Http\Message\ResponseInterface;
use Throwable;
use Hyperf\Di\Annotation\Inject;

class ValidationExceptionHandler extends Handler
{
    /**
     * @var StdoutLoggerInterface
     * @Inject()
     */
    protected $logger;

    public function handle(Throwable $throwable, ResponseInterface $response)
    {

        $msg = $throwable->validator->errors()->first();
        $code = 422;
        $this->stopPropagation();
//        var_dump("valid".$code);
        // return $msg;
        return $response->withAddedHeader('content-type', 'application/json; charset=utf-8')
            ->withBody(new SwooleStream(Json::encode(compact('code', 'msg'))));
    }
}
